package com.tbynet.jwp.service.provider;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.model.Comments;
import com.tbynet.jwp.service.CommentService;

import java.util.List;

public class CommentServiceProvider implements CommentService {

	@Override
	public int count(Object postId) {
		return Db.queryInt("select count(*) from wp_comments where comment_post_ID=?", postId);
	}

	@Override
	public List<Record> get_pending_comments_num(String[] postIds) {
		String sql = "SELECT comment_post_ID, COUNT(comment_ID) as num_comments FROM wp_comments WHERE comment_post_ID IN";
		if(null == postIds) {
			sql += " ( '' ) ";
		} else {
			sql += " ( " + StrKit.join(postIds, ",") + " ) ";
		}
		sql += "AND comment_approved = '0' GROUP BY comment_post_ID";
		return Db.query(sql);
	}

	@Override
	public Long get_comment_ids(String status) {
		String sql = "SELECT COUNT(*) FROM wp_comments WHERE ( ? ) ORDER BY wp_comments.comment_date_gmt DESC";
		return Db.queryLong(sql, Comments.assembleCommentApprovedClauses(status));
	}

	@Override
	public Page<Record> get_comment_ids(String status, int pageNumber, int pageSize) {
		String sql = "FROM wp_comments WHERE ( ? ) ORDER BY wp_comments.comment_date_gmt DESC";
		return Db.paginate(pageNumber, pageSize, "SELECT wp_comments.comment_ID", sql, Comments.assembleCommentApprovedClauses(status));
	}

	@Override
	public List<Record> get_comment_count() {
		return Db.query("SELECT comment_approved, COUNT( * ) AS total FROM wp_comments GROUP BY comment_approved");
	}

}
